﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.IO;

namespace ElectronicPolice
{
    public partial class Form1 : Form
    {
        private string picDir = "tempPics";     //临时图片目录
        private string videoPath;   //视频路径
        public Form1()
        {
            InitializeComponent();
        }

        //点击上传视频按钮
        private void btnUploadVideo_Click(object sender, EventArgs e)
        {
            if(openFileDialogVideo.ShowDialog() == DialogResult.OK)
            {
                videoPath = openFileDialogVideo.FileName;
                lblVideoFileName.Text = openFileDialogVideo.SafeFileName;
            }
        }

        //从视频中提取图片
        public async void GetPicFromVideo(string videoPath, string WidthAndHeight)
        {
            Process process = new Process();
            process.StartInfo.FileName = "ffmpeg.exe";//ffmpeg执行文件的路径
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.Arguments = " -i " + videoPath                    //视频路径
                                + " -r 1"                               //提取图片的频率，1秒提取1帧
                                + " -s " + WidthAndHeight             //设置图片的分辨率
                                + " " + picDir +@"/%d.jpg"; //输出的图片文件名

            await Task.Run(() =>
            {
                try
                {
                    if (lblProgress.InvokeRequired)
                    {
                        this.lblProgress.Invoke(new Action(() => { lblProgress.Text = "正在截图"; }));
                    }
                    process.Start();
                    process.WaitForExit(5000);
                    process.Close();
                    process.Dispose();
                    if (lblProgress.InvokeRequired)
                    {
                        this.lblProgress.Invoke(new Action(() => { lblProgress.Text = "截图完成"; }));
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });
        }

        //点击开始检测按钮
        private void btnStartJudge_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(picDir))
            {
                Directory.Delete(picDir);
            }
            Directory.CreateDirectory(picDir);
            GetPicFromVideo(videoPath, "705x576");
            /*if (Directory.Exists(picDir))
            {
                Directory.Delete(picDir);
            }*/
        }
    }
}
